package modele;

import java.util.ArrayList;
import java.util.NoSuchElementException;

public abstract class ResourcePool<R extends Resource> {
	protected final ArrayList<R> availableResource;
	protected final ArrayList<R> inUseResource;

	protected abstract R createRessource();

	public ResourcePool(int nb) {
		availableResource = new ArrayList<R>(nb);
		inUseResource = new ArrayList<R>(nb);
		for (int i = 0; i < nb; ++i)
			availableResource.add(createRessource());
	}

	public R provideRessource() {
		try{
			R res = availableResource.get(0);
			inUseResource.add(res);
			availableResource.remove(res);
			return res;
		}
		catch(IndexOutOfBoundsException e){
			throw new NoSuchElementException();
		}
	}

	public void freeResource(R res) {
		int i = inUseResource.indexOf(res);
		if (i == -1)
			throw new IllegalArgumentException("Ressource " + res
					+ " was not part of this pool");
		inUseResource.remove(res);
		availableResource.add(res);
	}

	public boolean hasAvailableResource() {
		return !availableResource.isEmpty();
	}

}
